<template>
  <view>
    <!-- 选择收货地址按钮区域 -->
    <view class="choose_address_box" v-if="isHaveAddress">
      <van-button type="info" size="small" @click="chooseAddress">+ 选择收货地址</van-button>
    </view>

    <view v-else class="address_box">
      <!-- 收货人联系电话 -->
      <view class="box1">
        <text>收货人：{{ addressInfo.userName }}</text>
        <view @click="chooseAddress">
          <text>联系电话: {{ addressInfo.telNumber }}</text>
          <van-icon name="arrow" />
        </view>
      </view>
      <!-- 收货地址 -->
      <view class="box2">收货地址：{{ addressStr }}</view>
    </view>

    <!-- 分割线 -->
    <image src="/static/images/cart_border@2x.png" class="sep_line" />

    <!-- 商品列表区域 -->
    <view>
      <block v-for="(item, index) in cart" :key="index">
        <van-card :num="item.count" :price="item.price" :title="item.name" :thumb="item.pic" />
      </block>
    </view>

    <!-- 登录后下载 -->
    <van-button
      type="primary"
      size="large"
      class="btnLogin"
      open-type="getUserInfo"
      v-if="isSubmit"
      @getuserinfo="orderSubmit"
    >登录后下载</van-button>

    <van-submit-bar v-else :price="allPrice" button-text="提交订单" @submit="onSubmit" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      addressInfo: null,
      cart: [],
      isSubmit: true
    }
  },
  onLoad() {
    // 页面加载期间读取本地的收货地址
    this.addressInfo = uni.getStorageSync('address') || null

    // 获取勾选后的商品
    this.cart = getApp().globalData.cart.filter((item) => item.isCheck)
  },
  methods: {
    // 选择收货地址
    async chooseAddress() {
      const [err, res] = await uni.chooseAddress()

      if (err) {
        uni.showToast({
          title: '地址获取失败',
          icon: 'none'
        })
      }

      this.addressInfo = res
      uni.setStorageSync('address', res)
    },

    // 登录获取 token功能
    async orderSubmit(userInfo) {
      // 获取用户登录后相关的参数
      if (userInfo.detail.errMsg !== 'getUserInfo:ok') {
        return uni.showToast({
          title: '登录失败',
          icon: 'none'
        })
      }

      // 获取用户登录凭证
      const [err, loginRes] = await uni.login()
      if (err) {
        return uni.showToast({
          title: '登录失败',
          icon: 'none'
        })
      }

      // 拼接发起支付的参数
      const loginParams = {
        code: loginRes.code,
        encryptedData: userInfo.detail.encryptedData,
        iv: userInfo.detail.iv,
        rawData: userInfo.detail.rawData,
        signature: userInfo.detail.signature
      }

      const loginData = await this.request({
        url: '/users/wxlogin',
        method: 'POST',
        data: loginParams
      })

      if (loginData.meta.status !== 200) {
        return uni.showToast({
          title: '登录失败',
          icon: 'none'
        })
      }

      uni.setStorageSync('token', loginData.message.token)

      this.isSubmit = false
    },

    // 创建订单和支付方法
    async onSubmit() {
      if (this.addressInfo === null) {
        return uni.showToast({
          title: '请选择收货地址！',
          icon: 'none'
        })
      }

      if (this.allPrice <= 0) {
        return uni.showToast({
          title: '订单创建失败！',
          icon: 'none'
        })
      }

      const createOrderRes = await this.request({
        url: '/my/orders/create',
        method: 'POST',
        header: {
          Authorization: uni.getStorageSync('token')
        },
        data: {
          order_price: '0.01',
          consignee_addr: this.addressStr,
          order_detail: JSON.stringify(this.cart),
          goods: this.cart.map((item) => {
            return {
              goods_id: item.id,
              goods_number: item.count,
              goods_price: item.price
            }
          })
        }
      })

      if (createOrderRes.meta.status !== 200) {
        return uni.showToast({
          title: '订单提交失败',
          icon: 'none'
        })
      }

      // 发起预支付
      const betaPayRes = await this.request({
        url: '/my/orders/req_unifiedorder',
        method: 'POST',
        header: {
          Authorization: uni.getStorageSync('token')
        },
        data: {
          order_number: createOrderRes.message.order_number
        }
      })

      if (betaPayRes.meta.status !== 200) {
        return uni.showToast({
          title: '订单提交失败',
          icon: 'none'
        })
      }

      // 调用微信支付 API
      const [err, payRes] = await uni.requestPayment(betaPayRes.message.pay)

      if (err) {
        return uni.showToast({
          title: '取消支付',
          icon: 'none'
        })
      }

      if (payRes.errMsg !== 'requestPayment:ok') {
        return uni.showToast({
          title: '支付支付',
          icon: 'none'
        })
      }

      uni.showToast({
        title: '支付成功',
        duration: 100,
        success() {
          uni.navigateTo({
            url: '/pages/orderlist/orderlist'
          })
        }
      })
    }
  },
  computed: {
    // 渲染收货地址
    addressStr() {
      if (this.addressInfo === null) {
        return ''
      }

      // 将收货地址进行拼接
      return (
        this.addressInfo.provinceName +
        this.addressInfo.cityName +
        this.addressInfo.countyName +
        this.addressInfo.detailInfo
      )
    },

    // 使用计算属性决定展示选择地址按钮还是渲染地址区域
    isHaveAddress() {
      if (this.addressInfo === null) {
        return true
      }

      return false
    },

    // 计算已勾选商品的价格
    allPrice() {
      let price = 0

      this.cart.forEach((item) => {
        if (item.isCheck) {
          price += item.price * item.count
        }
      })

      return price * 100
    }
  }
}
</script>
<style lang="less">
.choose_address_box {
  text-align: center;
  padding: 60rpx 0;
}

.sep_line {
  height: 7px;
  width: 100%;
  display: block;
}

.address_box {
  font-size: 26rpx;
  padding: 0 10rpx;

  .box1 {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0;
  }

  .box2 {
    padding-bottom: 30rpx;
  }
}
.btnLogin {
  position: fixed;
  bottom: 0;
  width: 100%;
}

.order_container {
  padding-bottom: 50px;
}
</style>
